package handler

import (
	"avatar-hub/cache"
	"avatar-hub/moder"
	"encoding/json"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

func UserAdd(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	user := moder.User{
		Username: username,
		Password: password,
	}
	moder.DB.Create(&user)
	c.JSON(200, gin.H{
		"mas":  "成功",
		"code": 200,
		"data": user,
	})
	return
}

func UserList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))
	offset := (page - 1) * size
	var user []moder.User
	redis_key := "redis_list" + strconv.Itoa(page)
	result, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if result == "" {
		moder.DB.Offset(offset).Limit(size).Order("id asc").Find(&user)
		jsonDat, _ := json.Marshal(user)
		cache.Rdb.Set(cache.Ctx, result, jsonDat, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &user)
	}
	var total int64

	moder.DB.Model(&moder.User{}).Count(&total)
	c.JSON(200, gin.H{
		"mas":   "成功",
		"code":  200,
		"data":  user,
		"total": total,
	})
	return
}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var user moder.User
	redis_key := "redis_detail" + id
	result, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if result == "" {
		moder.DB.Where("id=?", id).First(&user)
		jsonDat, _ := json.Marshal(user)
		cache.Rdb.Set(cache.Ctx, result, jsonDat, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &user)
	}

	c.JSON(200, gin.H{
		"mas":  "成功",
		"code": 200,
		"data": user,
	})
	return
}
